exports.add=[{
        _type:"functions",
        _section:"ajajform",
	/*
	 * Function: ajajform.parse_grids
	 *		Parses ajajform grids in space.fields and returns them as an object
	 *
	 * Returns:
	 *		Hash of grids, each grid is hash of hashes
	 */
/*	parse_grids: function(space) {
		var hashes={};
		for (var p in space.fields) {
			var arr;
			if (!(arr=p.match(/^(\w+)-([\w\.]+)-(\w+)$/))) continue;
			if (!hashes[arr[1]]) hashes[arr[1]]={};
			if (!hashes[arr[1]][arr[2]]) hashes[arr[1]][arr[2]]={};
			hashes[arr[1]][arr[2]][arr[3]]=space.fields[p];
		}
		return hashes;
	},*/

	/**
	 * Function: ajajform.parse_grid_json
	 *
	 */
	parse_grid: function(name) {
		var r={};
		var parse=JSON.parse(this.fields[name]);
		for (var k in parse) {
			if (!(arr=k.match(/^([\w\.]+)-(\w+)$/))) throw "Strange";
			if (!r[arr[1]]) r[arr[1]]={};
			r[arr[1]][arr[2]]=parse[k];
		}
		return r;
	},

	/*
	 * Function: functions.save_grid
	 *		Saves parsed grid
	 *
	 * Parameters:
	 *		grid								- A hash of hashes, representing a grid
	 *		modelname typeof String				- a name of model
	 *		rules								- hash of:
	 *		rules.existing_list typeof String	- 
	 *		rules.existing typeof function		- function() returning List fetch arguments
	 *		rules.insert typeof function		- function(premodel,id) filling premodel Object
	 *		rules.update typeof function		- function(premodel,id) filling premodel Object
	 *		rules.delete typeof function		- function(model)
	 *
	 * Returns:
	 *		none
	 */
	save_grid: function (grid,modelname,rules) {
		var ex={};
/*		if (mod) {
			exlist=space.mfact.list(mod[1],rules.existing());
		} else {
			exlist=space.site.sql.execute_and_fetch(sqlpath+"/list",rules.existing());
		}*/
		this.site.models[modelname].List(rules.existing_list,rules.existing()).forEach(function(p) {ex[p.id]=1;});
		for (var id in grid) {
			var hash=grid[id];
			var m;
			if (id.match(/new/)) {
				if (rules.insert) rules.insert(hash,id);
				m=this.site.models[modelname].Create(hash);
				m.SaveAll();
			} else {
				if (rules.update) rules.update(hash,id);
				m=this.site.models[modelname].Get(id);
				m.ApplyAdminFields(hash);
				m.SaveAll();
				delete ex[id];
			}
		}
		for (var id in ex) {
			var hash={};
			var m=this.site.models[modelname].Get(id);
			if (rules["delete"]) rules["delete"](m);
			m.Delete();
		}
	},
	/*
		Function: functions.reorder_grids
		Parameters:
			sqlprexix
	*/
	reorder_grids: function(space,sqlprefix) {
		var arr=[];
		var val=[];
		space.fields.ordering.split(/,/).forEach(function(x) {
			arr.push(x.match(/-(\d+)$/)[1]);
		});
		for (var i=0;i!=arr.length;i++) {
			val.push(1*(space.site.sql.execute_and_fetch_one(sqlprefix+"get_ordering",{id:arr[i]}).ordering));
			space.site.sql.execute(sqlprefix+"set_ordering",{id:arr[i],ordering: -i-1});
		}
		val.sort(function(a,b) {return a - b;});
		for (var i=0;i!=arr.length;i++) {
			space.site.sql.execute(sqlprefix+"set_ordering",{id:arr[i],ordering: val[i]});
		}
	}
}];

